package com.movie.controller;

import com.movie.dto.ChangePasswordRequest;
import com.movie.dto.UserDTO;
import com.movie.entity.User;
import com.movie.service.UserService;
import com.movie.service.OrderService;
import com.movie.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;

import java.util.HashMap;
import java.util.Map;
import org.springframework.security.authentication.BadCredentialsException;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public ResponseEntity<UserDTO> registerUser(@RequestBody User user) {
        // 添加输入校验
        User registeredUser = userService.register(user);
        // 创建 UserDTO 并返回
        UserDTO userDTO = new UserDTO();
        userDTO.setId(registeredUser.getId());
        userDTO.setUsername(registeredUser.getUsername());
        userDTO.setEmail(registeredUser.getEmail());
        userDTO.setRegisterTime(registeredUser.getRegisterTime());
        return ResponseEntity.ok(userDTO);
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        try {
            // 使用 AuthenticationManager 进行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
            );

            // 如果认证成功，Spring Security 会将认证信息存入 SecurityContextHolder
            // 我们可以从认证信息中获取 UserDetails
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();

            // 生成 JWT
            final String jwt = jwtUtil.generateToken(userDetails);

            // 返回 JWT (通常放在 JSON Body 中)
            return ResponseEntity.ok(Map.of("token", jwt));

        } catch (Exception e) {
            // 认证失败 (例如密码错误)
            return ResponseEntity.status(401).body("Invalid credentials");
        }
    }

    @GetMapping("/profile")
    public ResponseEntity<UserDTO> getUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).build(); // 或者抛出异常
        }

        String username = authentication.getName();
        User user = userService.findByUsername(username);

        if (user == null) {
            // 理论上不应发生，因为用户已认证
            return ResponseEntity.status(404).build();
        }

        // 创建 UserDTO 并返回 (确保 userService.findByUsername 返回了完整信息)
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setUsername(user.getUsername());
        userDTO.setEmail(user.getEmail());
        userDTO.setPhone(user.getPhone());
        userDTO.setAddress(user.getAddress());
        userDTO.setBalance(user.getBalance()); // 添加余额信息
        userDTO.setRegisterTime(user.getRegisterTime());

        return ResponseEntity.ok(userDTO);
    }

    @PutMapping("/profile")
    public ResponseEntity<UserDTO> updateUserProfile(@RequestBody UserDTO userUpdateDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).build();
        }
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return ResponseEntity.status(404).build();
        }

        User userToUpdate = new User();
        userToUpdate.setId(currentUser.getId());
        userToUpdate.setEmail(userUpdateDTO.getEmail());
        userToUpdate.setPhone(userUpdateDTO.getPhone());
        userToUpdate.setAddress(userUpdateDTO.getAddress());

        User updatedUser = userService.updateUserProfile(userToUpdate);

        UserDTO responseDTO = new UserDTO();
        responseDTO.setId(updatedUser.getId());
        responseDTO.setUsername(updatedUser.getUsername());
        responseDTO.setEmail(updatedUser.getEmail());
        responseDTO.setPhone(updatedUser.getPhone());
        responseDTO.setAddress(updatedUser.getAddress());
        responseDTO.setRegisterTime(updatedUser.getRegisterTime());

        return ResponseEntity.ok(responseDTO);
    }

    @PostMapping("/profile/change-password")
    public ResponseEntity<?> changePassword(@RequestBody ChangePasswordRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body(Map.of("message", "用户未登录"));
        }
        String username = authentication.getName();

        try {
            boolean success = userService.changePassword(username, request.getCurrentPassword(), request.getNewPassword());
            if (success) {
                return ResponseEntity.ok(Map.of("message", "Password changed successfully"));
            } else {
                // This case might not be reached if service throws exceptions
                return ResponseEntity.badRequest().body(Map.of("message", "密码修改失败"));
            }
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(401).body(Map.of("message", "当前密码错误"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "服务器内部错误"));
        }
    }

    // 充值余额
    @PostMapping("/balance/recharge")
    public ResponseEntity<?> rechargeBalance(@RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body(Map.of("message", "用户未登录"));
        }

        String username = authentication.getName();
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.status(404).body(Map.of("message", "用户不存在"));
        }

        try {
            // 获取充值金额
            BigDecimal amount = new BigDecimal(request.get("amount").toString());
            System.out.println("充值金额: " + amount);
            System.out.println("用户ID: " + user.getId());
            System.out.println("当前余额: " + user.getBalance());

            // 调用服务层处理充值
            User updatedUser = userService.rechargeBalance(user.getId(), amount);
            System.out.println("充值后余额: " + updatedUser.getBalance());

            // 创建返回DTO
            UserDTO userDTO = new UserDTO();
            userDTO.setId(updatedUser.getId());
            userDTO.setUsername(updatedUser.getUsername());
            userDTO.setEmail(updatedUser.getEmail());
            userDTO.setPhone(updatedUser.getPhone());
            userDTO.setAddress(updatedUser.getAddress());
            userDTO.setBalance(updatedUser.getBalance());
            userDTO.setRegisterTime(updatedUser.getRegisterTime());

            System.out.println("返回DTO: " + userDTO);

            // 使用HashMap而不是Map.of，因为Map.of有限制
            Map<String, Object> response = new HashMap<>();
            response.put("message", "充值成功");
            response.put("user", userDTO);

            return ResponseEntity.ok(response);
        } catch (NumberFormatException e) {
             return ResponseEntity.badRequest().body(Map.of("message", "充值金额格式错误"));
        } catch (IllegalArgumentException e) {
             return ResponseEntity.badRequest().body(Map.of("message", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("message", "服务器内部错误"));
        }
    }

    // 扣减余额
    @PostMapping("/balance/deduct")
    public ResponseEntity<?> deductBalance(@RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body(Map.of("message", "用户未登录"));
        }

        String username = authentication.getName();
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.status(404).body(Map.of("message", "用户不存在"));
        }

        try {
            // 获取扣减金额
            BigDecimal amount = new BigDecimal(request.get("amount").toString());

            // 调用服务层处理扣减
            User updatedUser = userService.deductBalance(user.getId(), amount);

            // 创建返回DTO
            UserDTO userDTO = new UserDTO();
            userDTO.setId(updatedUser.getId());
            userDTO.setUsername(updatedUser.getUsername());
            userDTO.setEmail(updatedUser.getEmail());
            userDTO.setPhone(updatedUser.getPhone());
            userDTO.setAddress(updatedUser.getAddress());
            userDTO.setBalance(updatedUser.getBalance());
            userDTO.setRegisterTime(updatedUser.getRegisterTime());

            // 使用HashMap而不是Map.of，因为Map.of有限制
            Map<String, Object> response = new HashMap<>();
            response.put("message", "扣减成功");
            response.put("user", userDTO);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(Map.of("message", e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "扣减失败，请稍后再试"));
        }
    }

    // 新增：处理提现请求
    @PostMapping("/balance/withdraw")
    public ResponseEntity<?> withdrawBalance(@RequestBody Map<String, Object> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body(Map.of("message", "用户未登录"));
        }

        String username = authentication.getName();
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.status(404).body(Map.of("message", "用户不存在"));
        }

        try {
            BigDecimal amount = new BigDecimal(request.get("amount").toString());

            if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                 return ResponseEntity.badRequest().body(Map.of("message", "提现金额必须大于0"));
            }

            // 调用服务层处理提现
            User updatedUser = userService.withdrawBalance(user.getId(), amount);

            // 创建返回DTO
            UserDTO userDTO = new UserDTO();
            userDTO.setId(updatedUser.getId());
            userDTO.setUsername(updatedUser.getUsername());
            userDTO.setEmail(updatedUser.getEmail());
            userDTO.setPhone(updatedUser.getPhone());
            userDTO.setAddress(updatedUser.getAddress());
            userDTO.setBalance(updatedUser.getBalance());
            userDTO.setRegisterTime(updatedUser.getRegisterTime());

            // 使用HashMap而不是Map.of
            Map<String, Object> response = new HashMap<>();
            response.put("message", "提现成功");
            response.put("user", userDTO); // 返回更新后的用户信息

            return ResponseEntity.ok(response);
        } catch (NumberFormatException e) {
             return ResponseEntity.badRequest().body(Map.of("message", "提现金额格式错误"));
        } catch (IllegalStateException e) { // 捕获余额不足等业务异常
             return ResponseEntity.badRequest().body(Map.of("message", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace(); // 记录详细错误
            return ResponseEntity.status(500).body(Map.of("message", "服务器内部错误，提现失败"));
        }
    }
}